package com.ScroringSystem.backend.service;

import com.ScroringSystem.backend.mapper.ContestantMapper;
import com.ScroringSystem.backend.pojo.Contestant;
import com.ScroringSystem.backend.pojo.UpdateScoreReq;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Wrapper;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
public class ContestantService {
    private final ContestantMapper contestantMapper;

    @Autowired
    public ContestantService(ContestantMapper contestantMapper) {
        this.contestantMapper = contestantMapper;
    }

    @Transactional
    public void updateScore(UpdateScoreReq updateScoreReq) {
        Integer userId = updateScoreReq.getUserId();
        BigDecimal score = updateScoreReq.getScore();
        String judge = updateScoreReq.getJudge();
        String AllJudge;
        if (userId == null) {
            throw new IllegalArgumentException("userId cant be null");
        }
        if (score == null) {
            throw new IllegalArgumentException("score cant be null");
        }

        Contestant contestant = contestantMapper.selectOne(Wrappers.<Contestant>lambdaQuery()
                .eq(Contestant::getUserId,userId));
        if (contestant == null) {
            throw new IllegalArgumentException("Contestant with userId " + userId + " does not exist.");
        }

        BigDecimal newScore = contestant.getScore().add(score);
        Integer times = contestant.getTimes() + 1;
        BigDecimal submitted = newScore.divide(BigDecimal.valueOf(times), BigDecimal.ROUND_CEILING);
        Contestant updateContestant = new Contestant();
        AllJudge=judge+"("+score+")"+","+contestant.getJudge();
        updateContestant.setJudge(AllJudge);
        updateContestant.setId(contestant.getId());
        updateContestant.setScore(newScore);
        updateContestant.setTimes(times);
        updateContestant.setSubmitted(submitted);
        contestantMapper.updateById(updateContestant);
    }

    public List<Contestant> listContestant() {
        return contestantMapper.selectList(new LambdaQueryWrapper<>());
    }


    public List<Contestant> showContestant() {
        return contestantMapper.selectOrderBy();
    }

    public int countContestant(){ return contestantMapper.countSelect();}
}

